package com.znfeiche.server.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.znfeiche.exception.XMLCRUDException;
import com.znfeiche.server.DAO.WebDAO;
import com.znfeiche.server.DO.InitParam;
import com.znfeiche.server.DO.WebDO;

/**
 * 保存服务端相关信息
 * @author soft01
 *
 */
public class ServerContext {
	/**
	 * 请求与Servlet之间的映射
	 * key:请求路径
	 * value：对应的Servlet名字
	 */
	private static Map<String,String>servletMapping = new HashMap<String,String>();
	static {
//		initServletMapping();
		initServerContext();
	}
	private static void initServerContext(){
		WebDAO webDAO = new WebDAO();
		WebDO web = new WebDO();
		web.setFilter("111");
		InitParam initParam = new InitParam();
		initParam.setParamName("00");
		initParam.setParamValue("222");
		web.setInitParam(initParam);
		web.setId("1");
		try {
			webDAO.insertSelective(web);
		} catch (XMLCRUDException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 初始化Servlet映射
	 */
	private static void initServletMapping() {
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read("conf/servlets.xml");
			Element root = doc.getRootElement();
			List<Element>serEle = root.elements("servlet");
			for(Element ele:serEle) {
				String key = ele.attributeValue("url");
				String value = ele.attributeValue("class");
				servletMapping.put(key, value);
			}
			System.out.println(servletMapping.size());
			Set<Entry<String,String>>entry = servletMapping.entrySet();
			for(Entry<String,String>e:entry) {
				System.out.println(e.getKey()+","+e.getValue());
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 根据给定的url获取对应的Servlet名字
	 * @param url
	 * @return
	 */
	public static String getServletByUrl(String url) {
		return servletMapping.get(url);
	}
	/**
	 * 判断此url是否对应一个Servlet
	 * @param url
	 * @return
	 */
	public static boolean hasUrl(String url) {
		return servletMapping.containsKey(url);
	}
	public static void main(String[] args) {
		System.out.println("完成");
	}
	
}
